package com.smart.campus.web.controller.wx;

import com.alibaba.fastjson.JSON;
import com.qiniu.storage.model.DefaultPutRet;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.config.Global;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.core.page.TableDataInfo;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.framework.util.QiNiuFileOptUtil;
import com.smart.campus.framework.web.service.DictService;
import com.smart.campus.school.domain.*;
import com.smart.campus.school.domain.query.IllegalRecordQuery;
import com.smart.campus.school.domain.vo.*;
import com.smart.campus.school.service.*;
import com.smart.campus.system.domain.SysDictData;
import com.smart.campus.system.domain.SysUser;
import com.smart.campus.system.service.ISysUserService;
import com.smart.campus.web.utils.SchoolUtil;
import com.smart.campus.web.utils.StudentUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 微信api
 */
@RestController
@RequestMapping("/wx/api")
@CrossOrigin(origins = "*",maxAge = 3600)
public class WxApiController extends BaseController {


    @Autowired
    private ISysUserService userService;

    @Autowired
    private ITeacherApplyListService applyListService;

    @Autowired
    private IApplyListService iApplyListService;
    @Autowired
    private IApproveListService approveListService;

    @Autowired
    private IPersonnelInfoService personnelInfoService;

    @Autowired
    private IAdjustCourseService adjustCourseService;

    @Autowired
    private IIllegalRecordService iIllegalRecordService;

    @Autowired
    private IClockInRecordService clockInRecordService;

    @Autowired
    private IStudentService studentService;
    @Autowired
    private ICourseMainConfigService courseMainConfigService;

    @Autowired
    private ICourseItemConfigService courseItemConfigService;
    @Autowired
    private DictService dictService;

    @GetMapping("/getTeacherByOpenId")
    @ResponseBody
    public SysUser getTeacherByOpenId(String openId)
    {

        SysUser user = this.userService.findByOpenId(openId);
        return user;
    }
    @GetMapping("/getTeacherById")
    @ResponseBody
    public SysUser getTeacherById(String id)
    {
        SysUser user = this.userService.selectUserById(Long.parseLong(id));
        return user;
    }
    /**
     * 新增保存老师请假申请
     */
    @Log(title = "微信端老师请假申请", businessType = BusinessType.INSERT)
    @PostMapping("/addSaveByWechat")
    @ResponseBody
    public AjaxResult addSaveByWechat(TeacherApplyList applyList)
    {

        //applyList.setSchoolId(SchoolUtil.getSchoolId());

        return toAjax(applyListService.insertWechatTeacherApplyList(applyList));
    }

    /**
     * 查询老师的所有请假记录
     * @param teacherId
     * @return
     */
    @PostMapping("/getApplyListByTeacherId")
    @ResponseBody
    public AjaxResult getApplyListByTeacherId(Long teacherId)
    {
        TeacherApplyList teacherApplyList = new TeacherApplyList();
        teacherApplyList.setTeacherId(teacherId);
        List<TeacherApplyList> list = applyListService.selectTeacherApplyListList(teacherApplyList);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询请假记录成功",list);


        return res;
    }

    /**
     * 查询需要我审批的老师提交的请假记录
     * @param userId
     * @return
     */
    @PostMapping("/getApplyListByApproverUserId")
    @ResponseBody
    public AjaxResult getApplyListByApproverUserId(String userId)
    {
        TeacherApplyList teacherApplyList = new TeacherApplyList();
        teacherApplyList.setApproverIds(userId);
        List<TeacherApplyList> list = applyListService.selectTeacherApplyListList(teacherApplyList);
        AdjustCourse adjustCourse = new AdjustCourse();
        adjustCourse.setApproverIds("17");
        List<AdjustCourse> adjustCourseList = adjustCourseService.selectAdjustCourseList(adjustCourse);
        if(CollectionUtils.isNotEmpty(adjustCourseList)){
            for (AdjustCourse course : adjustCourseList) {
                TeacherApplyList applyList = new TeacherApplyList();
                applyList.setStatus(course.getStatus());
                applyList.setType(3);
                applyList.setId(course.getId());
                applyList.setBeginTime(course.getBeginTime());
                applyList.setEndTime(course.getEndTime());
                applyList.setCreateTime(course.getCreateTime());
                applyList.setReason(course.getReason());
                applyList.setTeacherName(course.getTeacherName());
                list.add(applyList);
            }
        }
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询需要我审批的请假记录成功",list);

        return res;
    }
    /**
     * 查询需要我审批的老师提交的当前还没审批请假记录
     * @param userId
     * @return
     */
    @PostMapping("/getUnhandleApplyListByApproverUserId")
    @ResponseBody
    public AjaxResult getUnhandleApplyListByApproverUserId(String userId)
    {
        TeacherApplyList teacherApplyList = new TeacherApplyList();
        teacherApplyList.setApproverIds(userId);
        teacherApplyList.setStatus(1);
        List<TeacherApplyList> list = applyListService.selectTeacherApplyListList(teacherApplyList);
        AdjustCourse adjustCourse = new AdjustCourse();
        adjustCourse.setApproverIds("17");
        adjustCourse.setStatus(1);
        List<AdjustCourse> adjustCourseList = adjustCourseService.selectAdjustCourseList(adjustCourse);
        if(CollectionUtils.isNotEmpty(adjustCourseList)){
            for (AdjustCourse course : adjustCourseList) {
                TeacherApplyList applyList = new TeacherApplyList();
                applyList.setStatus(course.getStatus());
                applyList.setType(3);
                applyList.setId(course.getId());
                applyList.setBeginTime(course.getBeginTime());
                applyList.setEndTime(course.getEndTime());
                applyList.setCreateTime(course.getCreateTime());
                applyList.setReason(course.getReason());
                applyList.setTeacherName(course.getTeacherName());
                list.add(applyList);
            }
        }
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询需要我审批的请假记录成功",list);

        return res;
    }

    /**
     * 查询老师的请假记录详情
     * @param id
     * @return
     */
    @PostMapping("/getApplyListById")
    @ResponseBody
    public AjaxResult getApplyListById(Long id)
    {
        TeacherApplyList teacherApplyList = this.applyListService.selectTeacherApplyListById(id);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询请假记录成功",teacherApplyList);

        return res;
    }

    /**
     * 查询调课记录详情
     * @param id
     * @return
     */
    @PostMapping("/getAdjustCourseById")
    @ResponseBody
    public AjaxResult getAdjustCourseById(Long id)
    {
        AdjustCourse adjustCourse = this.adjustCourseService.selectAdjustCourseById(id);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询调课记录成功",adjustCourse);

        return res;
    }

    /**
     * 微信端审批老师请假
     * @param approveList
     * @return
     */
    @PostMapping("/approveByWechat")
    @ResponseBody
    public AjaxResult approveByWechat(ApproveList approveList)
    {
        SysUser sysUser = this.userService.selectUserById(approveList.getApproveId());
        approveList.setApprover(sysUser.getUserName());
        //添加审批记录
        approveList.setType(2);
        approveListService.insertApproveList(approveList);

        TeacherApplyList applyList = this.applyListService.selectTeacherApplyListById(approveList.getApplyId());
        int status = SchoolUtil.getApplySpStatus(approveList.getStatus(),applyList.getStatus());
        applyList.setStatus(status);
        //修改请假审批状态
        applyListService.approveTeacherApplyList(applyList);

        return AjaxResult.success();
    }


    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = Global.getUploadPath();
            // 上传并返回新文件名称
            //String fileName = FileUploadUtils.upload(filePath, file);
            // String url = serverConfig.getUrl() + fileName;

            DefaultPutRet ret = QiNiuFileOptUtil.upload(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", ret.key);
            ajax.put("url", QiNiuFileOptUtil.URL+ret.key);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PostMapping("/updateTeachInfo")
    @ResponseBody
    public AjaxResult updateTeachInfo(SysUser user) throws Exception
    {
        try
        {
            userService.updateUserInfo(user);
            AjaxResult ajax = AjaxResult.success();
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    @Autowired
    private IScPaymentBillService scPaymentBillService;

    @Autowired
    private IWrongQuestionService wrongQuestionService;

    /**
     * 查询缴费单列表
     */
    @PostMapping("/getPaymentList")
    @ResponseBody
    public AjaxResult getPaymentList(Long userId,Integer status) {

        // userId = 1L;
        if(userId == null){
            return null;
        }
        ScPaymentBill scPaymentBill = new ScPaymentBill();
        scPaymentBill.setUserId(userId);
        scPaymentBill.setStatus(status);
        List<ScPaymentBill> list = scPaymentBillService.selectScPaymentBillList(scPaymentBill);
        return AjaxResult.success(list);
    }

    /**
     * 查询奖罚列表
     */
    @PostMapping("/getAwardList")
    @ResponseBody
    public AjaxResult getAwardList(Long userId,Integer type) {

        //userId = 1L;
        if(userId == null){
            return null;
        }
        IllegalRecordQuery query = new IllegalRecordQuery();
        query.setStudentId(userId);
        query.setType(type);
        List<IllegalRecordVo> list = iIllegalRecordService.selectIllegalRecordList(query);
        return AjaxResult.success(list);
    }

    /**
     * 查询考勤列表
     */
    @PostMapping("/getClockList")
    @ResponseBody
    public AjaxResult getClockList(Long userId,Integer type) {

        //userId = 1L;
        if(userId == null){
            return null;
        }
        ClockInRecord query = new ClockInRecord();
        query.setUserId(userId);
        query.setUserType(2);
        List<ClockInRecord> list = clockInRecordService.selectClockInRecordList(query);
        return AjaxResult.success(list);
    }

    /**
     * 获取学生信息
     */
    @GetMapping("/getStudentInfo")
    @ResponseBody
    public Student getStudentInfo(Long id) {

        Student student = studentService.selectStudentById(id);
        return student;
    }

    /**
     * 更新学生信息
     */
    @PostMapping("/updateStudentInfo")
    @ResponseBody
    public AjaxResult updateStudentInfo(Student student) {
        studentService.updateStudent(student);
        return AjaxResult.success(student);
    }


    /**
     * 获取老师某周的课程表
     * @param clazzId
     * @param studentId
     * @param beginWeek
     * @param endWeek
     * @return
     */
    @PostMapping("/getCourseByStudentId")
    @ResponseBody
    public Map<String,Object> getCourseByStudentId(Long clazzId, Long studentId, String beginWeek, String endWeek)
    {
        long startTime = System.currentTimeMillis();
        Student student = studentService.selectStudentById(studentId);
        Map<String,Object> res = new HashMap<>();
        List< Map<String,Object>> mapList = new ArrayList<>();
        Map<Integer, List<CourseItemConfigVo>> result = new HashMap<>();
        int bw = Integer.parseInt(beginWeek);
        int ew = Integer.parseInt(endWeek);
        if(bw>ew){
            return res;
        }
        CourseItemConfigVo courseItemConfig = new CourseItemConfigVo();
        Map params = new HashMap();
        params.put("bType",bw);
        params.put("eType",ew);
        courseItemConfig.setParams(params);
        courseItemConfig.setClazzId(student.getClassId());

        //获取当前班级对应的排课信息
        List<CourseItemConfigVo> list = courseItemConfigService.selectCourseItemConfigList(courseItemConfig);


        if(org.apache.commons.collections.CollectionUtils.isNotEmpty(list)){

            List<SysDictData> dictData = dictService.getType("sc_subject_type");
            Map<String,String> dict = dictData.stream().collect(Collectors.toMap(SysDictData::getDictValue,SysDictData::getDictLabel));
            for (CourseItemConfigVo courseItemConfigVo : list) {
               // String courseName = dictService.getLabel("sc_subject_type",courseItemConfigVo.getCourseId().toString());
                courseItemConfigVo.setCourseName(dict.get(courseItemConfigVo.getCourseId().toString()));
            }
            CourseMainConfigVo courseMainConfig = courseMainConfigService.selectCourseMainConfigById(list.get(0).getMainId());
            Map<String,Object> sectionCountMap = new HashMap<>();
            for (int i = 1; i <= courseMainConfig.getSections(); i++) {
                sectionCountMap.put("id",i);
                sectionCountMap.put("time", "第"+ i+"节");
                sectionCountMap.put("name1","");
                sectionCountMap.put("name2","");
                sectionCountMap.put("name3","");
                sectionCountMap.put("name4","");
                sectionCountMap.put("name5","");
                sectionCountMap.put("name6","");
                sectionCountMap.put("name7","");
            }
            res.put("sectionCount",sectionCountMap);
            //按节次分组(每节课一行)
            result = list.stream().collect(Collectors.groupingBy(CourseItemConfigVo::getSection));
            for (Map.Entry<Integer, List<CourseItemConfigVo>> entry : result.entrySet()) {
                Map<String,Object> sectionMap = new HashMap<>();
                sectionMap.put("section",entry.getKey());
                sectionMap.put("data",entry.getValue());
                mapList.add(sectionMap);
            }
            res.put("dataList",mapList);
        }
        long endTime = System.currentTimeMillis();
        logger.info("查询个人课表耗时:[{}]ms",endTime-startTime);
        return res;
    }


    /**
     * 新增保存老师请假申请
     */
    @Log(title = "微信端学生请假申请", businessType = BusinessType.INSERT)
    @PostMapping("/addApplyListByWechat")
    @ResponseBody
    public AjaxResult addApplyListByWechat(ApplyList applyList)
    {

        //applyList.setSchoolId(SchoolUtil.getSchoolId());

        return toAjax(iApplyListService.insertApplyList(applyList));
    }

    /**
     * 查询学生的所有请假记录
     * @param studentId
     * @return
     */
    @PostMapping("/getApplyListByStudentId")
    @ResponseBody
    public AjaxResult getApplyListByStudentId(Long studentId)
    {
        ApplyList applyList = new ApplyList();
        applyList.setStudentId(studentId);
        List<ApplyList> list = iApplyListService.selectApplyListList(applyList);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询请假记录成功",list);


        return res;
    }

    /**
     * 查询学生的请假记录详情
     * @param id
     * @return
     */
    @GetMapping("/getStudentApplyListById")
    @ResponseBody
    public AjaxResult getStudentApplyListById(Long id)
    {
        ApplyList applyList = this.iApplyListService.selectApplyListById(id);

        ApproveList approveList = new ApproveList();
        approveList.setApplyId(id);
        List<ApproveList> approveListList = approveListService.selectApproveListList(approveList);
        applyList.setApproveListList(approveListList);
        AjaxResult res = new AjaxResult(AjaxResult.Type.SUCCESS,"查询请假记录成功",applyList);

        return res;
    }

}
